home *** CD-ROM | disk | FTP | other *** search
/ The Atari Compendium / The Atari Compendium (Toad Computers) (1994).iso / files / prgtools / gnustuff / tos / bison / bisn119s.zoo / bison.info-3 < prev    next >
Encoding:
GNU Info File  |  1992-09-05  |  48.1 KB  |  1,256 lines

  1. This is Info file bison.info, produced by Makeinfo-1.47 from the input
  2. file /home/gd/gnu/bison/bison.texinfo.
  3.  
  4.    This file documents the Bison parser generator.
  5.  
  6.    Copyright (C) 1988, 1989, 1990 Free Software Foundation, Inc.
  7.  
  8.    Permission is granted to make and distribute verbatim copies of this
  9. manual provided the copyright notice and this permission notice are
  10. preserved on all copies.
  11.  
  12.    Permission is granted to copy and distribute modified versions of
  13. this manual under the conditions for verbatim copying, provided also
  14. that the sections entitled "GNU General Public License" and "Conditions
  15. for Using Bison" are included exactly as in the original, and provided
  16. that the entire resulting derived work is distributed under the terms
  17. of a permission notice identical to this one.
  18.  
  19.    Permission is granted to copy and distribute translations of this
  20. manual into another language, under the above conditions for modified
  21. versions, except that the sections entitled "GNU General Public
  22. License", "Conditions for Using Bison" and this permission notice may be
  23. included in translations approved by the Free Software Foundation
  24. instead of in the original English.
  25.  
  26. File: bison.info,  Node: Type Decl,  Next: Expect Decl,  Prev: Union Decl,  Up: Declarations
  27.  
  28. Nonterminal Symbols
  29. -------------------
  30.  
  31. When you use `%union' to specify multiple value types, you must declare
  32. the value type of each nonterminal symbol for which values are used. 
  33. This is done with a `%type' declaration, like this:
  34.  
  35.      %type <TYPE> NONTERMINAL...
  36.  
  37. Here NONTERMINAL is the name of a nonterminal symbol, and TYPE is the
  38. name given in the `%union' to the alternative that you want (*note
  39. Union Decl::.).  You can give any number of nonterminal symbols in the
  40. same `%type' declaration, if they have the same value type.  Use spaces
  41. to separate the symbol names.
  42.  
  43. File: bison.info,  Node: Expect Decl,  Next: Start Decl,  Prev: Type Decl,  Up: Declarations
  44.  
  45. Suppressing Conflict Warnings
  46. -----------------------------
  47.  
  48.    Bison normally warns if there are any conflicts in the grammar
  49. (*note Shift/Reduce::.), but most real grammars have harmless
  50. shift/reduce conflicts which are resolved in a predictable way and
  51. would be difficult to eliminate.  It is desirable to suppress the
  52. warning about these conflicts unless the number of conflicts changes. 
  53. You can do this with the `%expect' declaration.
  54.  
  55.    The declaration looks like this:
  56.  
  57.      %expect N
  58.  
  59.    Here N is a decimal integer.  The declaration says there should be no
  60. warning if there are N shift/reduce conflicts and no reduce/reduce
  61. conflicts.  The usual warning is given if there are either more or fewer
  62. conflicts, or if there are any reduce/reduce conflicts.
  63.  
  64.    In general, using `%expect' involves these steps:
  65.  
  66.    * Compile your grammar without `%expect'.  Use the `-v' option to
  67.      get a verbose list of where the conflicts occur.  Bison will also
  68.      print the number of conflicts.
  69.  
  70.    * Check each of the conflicts to make sure that Bison's default
  71.      resolution is what you really want.  If not, rewrite the grammar
  72.      and go back to the beginning.
  73.  
  74.    * Add an `%expect' declaration, copying the number N from the number
  75.      which Bison printed.
  76.  
  77.    Now Bison will stop annoying you about the conflicts you have
  78. checked, but it will warn you again if changes in the grammer result in
  79. additional conflicts.
  80.  
  81. File: bison.info,  Node: Start Decl,  Next: Pure Decl,  Prev: Expect Decl,  Up: Declarations
  82.  
  83. The Start-Symbol
  84. ----------------
  85.  
  86.    Bison assumes by default that the start symbol for the grammar is
  87. the first nonterminal specified in the grammar specification section. 
  88. The programmer may override this restriction with the `%start'
  89. declaration as follows:
  90.  
  91.      %start SYMBOL
  92.  
  93. File: bison.info,  Node: Pure Decl,  Next: Decl Summary,  Prev: Start Decl,  Up: Declarations
  94.  
  95. A Pure (Reentrant) Parser
  96. -------------------------
  97.  
  98.    A "reentrant" program is one which does not alter in the course of
  99. execution; in other words, it consists entirely of "pure" (read-only)
  100. code.  Reentrancy is important whenever asynchronous execution is
  101. possible; for example, a nonreentrant program may not be safe to call
  102. from a signal handler.  In systems with multiple threads of control, a
  103. nonreentrant program must be called only within interlocks.
  104.  
  105.    The Bison parser is not normally a reentrant program, because it uses
  106. statically allocated variables for communication with `yylex'.  These
  107. variables include `yylval' and `yylloc'.
  108.  
  109.    The Bison declaration `%pure_parser' says that you want the parser
  110. to be reentrant.  It looks like this:
  111.  
  112.      %pure_parser
  113.  
  114.    The effect is that the two communication variables become local
  115. variables in `yyparse', and a different calling convention is used for
  116. the lexical analyzer function `yylex'.  *Note Pure Calling::, for the
  117. details of this.  The variable `yynerrs' also becomes local in
  118. `yyparse' (*note Error Reporting::.).  The convention for calling
  119. `yyparse' itself is unchanged.
  120.  
  121. File: bison.info,  Node: Decl Summary,  Prev: Pure Decl,  Up: Declarations
  122.  
  123. Bison Declaration Summary
  124. -------------------------
  125.  
  126.    Here is a summary of all Bison declarations:
  127.  
  128. `%union'
  129.      Declare the collection of data types that semantic values may have
  130.      (*note Union Decl::.).
  131.  
  132. `%token'
  133.      Declare a terminal symbol (token type name) with no precedence or
  134.      associativity specified (*note Token Decl::.).
  135.  
  136. `%right'
  137.      Declare a terminal symbol (token type name) that is
  138.      right-associative (*note Precedence Decl::.).
  139.  
  140. `%left'
  141.      Declare a terminal symbol (token type name) that is
  142.      left-associative (*note Precedence Decl::.).
  143.  
  144. `%nonassoc'
  145.      Declare a terminal symbol (token type name) that is nonassociative
  146.      (using it in a way that would be associative is a syntax error)
  147.      (*note Precedence Decl::.).
  148.  
  149. `%type'
  150.      Declare the type of semantic values for a nonterminal symbol
  151.      (*note Type Decl::.).
  152.  
  153. `%start'
  154.      Specify the grammar's start symbol (*note Start Decl::.).
  155.  
  156. `%expect'
  157.      Declare the expected number of shift-reduce conflicts (*note
  158.      Expect Decl::.).
  159.  
  160. `%pure_parser'
  161.      Request a pure (reentrant) parser program (*note Pure Decl::.).
  162.  
  163. File: bison.info,  Node: Multiple Parsers,  Prev: Declarations,  Up: Grammar File
  164.  
  165. Multiple Parsers in the Same Program
  166. ====================================
  167.  
  168.    Most programs that use Bison parse only one language and therefore
  169. contain only one Bison parser.  But what if you want to parse more than
  170. one language with the same program?  Then you need to avoid a name
  171. conflict between different definitions of `yyparse', `yylval', and so
  172. on.
  173.  
  174.    The easy way to do this is to use the option `-p PREFIX' (*note
  175. Invocation::.).  This renames the interface functions and variables of
  176. the Bison parser to start with PREFIX instead of `yy'.  You can use
  177. this to give each parser distinct names that do not conflict.
  178.  
  179.    The precise list of symbols renamed is `yyparse', `yylex',
  180. `yyerror', `yylval', `yychar' and `yydebug'.  For example, if you use
  181. `-p c', the names become `cparse', `clex', and so on.
  182.  
  183.    *All the other variables and macros associated with Bison are not
  184. renamed.* These others are not global; there is no conflict if the same
  185. name is used in different parsers.  For example, `YYSTYPE' is not
  186. renamed, but defining this in different ways in different parsers causes
  187. no trouble (*note Value Type::.).
  188.  
  189.    The `-p' option works by adding macro definitions to the beginning
  190. of the parser source file, defining `yyparse' as `PREFIXparse', and so
  191. on.  This effectively substitutes one name for the other in the entire
  192. parser file.
  193.  
  194. File: bison.info,  Node: Interface,  Next: Algorithm,  Prev: Grammar File,  Up: Top
  195.  
  196. Parser C-Language Interface
  197. ***************************
  198.  
  199.    The Bison parser is actually a C function named `yyparse'.  Here we
  200. describe the interface conventions of `yyparse' and the other functions
  201. that it needs to use.
  202.  
  203.    Keep in mind that the parser uses many C identifiers starting with
  204. `yy' and `YY' for internal purposes.  If you use such an identifier
  205. (aside from those in this manual) in an action or in additional C code
  206. in the grammar file, you are likely to run into trouble.
  207.  
  208. * Menu:
  209.  
  210. * Parser Function:: How to call `yyparse' and what it returns.
  211. * Lexical::         You must supply a function `yylex' which reads tokens.
  212. * Error Reporting:: You must supply a function `yyerror'.
  213. * Action Features:: Special features for use in actions.
  214.  
  215. File: bison.info,  Node: Parser Function,  Next: Lexical,  Prev: Interface,  Up: Interface
  216.  
  217. The Parser Function `yyparse'
  218. =============================
  219.  
  220.    You call the function `yyparse' to cause parsing to occur.  This
  221. function reads tokens, executes actions, and ultimately returns when it
  222. encounters end-of-input or an unrecoverable syntax error.  You can also
  223. write an action which directs `yyparse' to return immediately without
  224. reading further.
  225.  
  226.    The value returned by `yyparse' is 0 if parsing was successful
  227. (return is due to end-of-input).
  228.  
  229.    The value is 1 if parsing failed (return is due to a syntax error).
  230.  
  231.    In an action, you can cause immediate return from `yyparse' by using
  232. these macros:
  233.  
  234. `YYACCEPT'
  235.      Return immediately with value 0 (to report success).
  236.  
  237. `YYABORT'
  238.      Return immediately with value 1 (to report failure).
  239.  
  240. File: bison.info,  Node: Lexical,  Next: Error Reporting,  Prev: Parser Function,  Up: Interface
  241.  
  242. The Lexical Analyzer Function `yylex'
  243. =====================================
  244.  
  245.    The "lexical analyzer" function, `yylex', recognizes tokens from the
  246. input stream and returns them to the parser.  Bison does not create
  247. this function automatically; you must write it so that `yyparse' can
  248. call it.  The function is sometimes referred to as a lexical scanner.
  249.  
  250.    In simple programs, `yylex' is often defined at the end of the Bison
  251. grammar file.  If `yylex' is defined in a separate source file, you
  252. need to arrange for the token-type macro definitions to be available
  253. there. To do this, use the `-d' option when you run Bison, so that it
  254. will write these macro definitions into a separate header file
  255. `NAME.tab.h' which you can include in the other source files that need
  256. it.  *Note Invocation::.
  257.  
  258. * Menu:
  259.  
  260. * Calling Convention::   How `yyparse' calls `yylex'.
  261. * Token Values::         How `yylex' must return the semantic value
  262.                            of the token it has read.
  263. * Token Positions::      How `yylex' must return the text position
  264.                            (line number, etc.) of the token, if the
  265.                            actions want that.
  266. * Pure Calling::         How the calling convention differs
  267.                            in a pure parser (*note Pure Decl::.).
  268.  
  269. File: bison.info,  Node: Calling Convention,  Next: Token Values,  Prev: Lexical,  Up: Lexical
  270.  
  271. Calling Convention for `yylex'
  272. ------------------------------
  273.  
  274.    The value that `yylex' returns must be the numeric code for the type
  275. of token it has just found, or 0 for end-of-input.
  276.  
  277.    When a token is referred to in the grammar rules by a name, that name
  278. in the parser file becomes a C macro whose definition is the proper
  279. numeric code for that token type.  So `yylex' can use the name to
  280. indicate that type.  *Note Symbols::.
  281.  
  282.    When a token is referred to in the grammar rules by a character
  283. literal, the numeric code for that character is also the code for the
  284. token type. So `yylex' can simply return that character code.  The null
  285. character must not be used this way, because its code is zero and that
  286. is what signifies end-of-input.
  287.  
  288.    Here is an example showing these things:
  289.  
  290.      yylex ()
  291.      {
  292.        ...
  293.        if (c == EOF)     /* Detect end of file. */
  294.          return 0;
  295.        ...
  296.        if (c == '+' || c == '-')
  297.          return c;      /* Assume token type for `+' is '+'. */
  298.        ...
  299.        return INT;      /* Return the type of the token. */
  300.        ...
  301.      }
  302.  
  303. This interface has been designed so that the output from the `lex'
  304. utility can be used without change as the definition of `yylex'.
  305.  
  306. File: bison.info,  Node: Token Values,  Next: Token Positions,  Prev: Calling Convention,  Up: Lexical
  307.  
  308. Semantic Values of Tokens
  309. -------------------------
  310.  
  311.    In an ordinary (nonreentrant) parser, the semantic value of the
  312. token must be stored into the global variable `yylval'.  When you are
  313. using just one data type for semantic values, `yylval' has that type.
  314. Thus, if the type is `int' (the default), you might write this in
  315. `yylex':
  316.  
  317.        ...
  318.        yylval = value;  /* Put value onto Bison stack. */
  319.        return INT;      /* Return the type of the token. */
  320.        ...
  321.  
  322.    When you are using multiple data types, `yylval''s type is a union
  323. made from the `%union' declaration (*note Union Decl::.).  So when you
  324. store a token's value, you must use the proper member of the union. If
  325. the `%union' declaration looks like this:
  326.  
  327.      %union {
  328.        int intval;
  329.        double val;
  330.        symrec *tptr;
  331.      }
  332.  
  333. then the code in `yylex' might look like this:
  334.  
  335.        ...
  336.        yylval.intval = value; /* Put value onto Bison stack. */
  337.        return INT;          /* Return the type of the token. */
  338.        ...
  339.  
  340. File: bison.info,  Node: Token Positions,  Next: Pure Calling,  Prev: Token Values,  Up: Lexical
  341.  
  342. Textual Positions of Tokens
  343. ---------------------------
  344.  
  345.    If you are using the `@N'-feature (*note Action Features::.) in
  346. actions to keep track of the textual locations of tokens and groupings,
  347. then you must provide this information in `yylex'.  The function
  348. `yyparse' expects to find the textual location of a token just parsed
  349. in the global variable `yylloc'.  So `yylex' must store the proper data
  350. in that variable.  The value of `yylloc' is a structure and you need
  351. only initialize the members that are going to be used by the actions. 
  352. The four members are called `first_line', `first_column', `last_line'
  353. and `last_column'.  Note that the use of this feature makes the parser
  354. noticeably slower.
  355.  
  356.    The data type of `yylloc' has the name `YYLTYPE'.
  357.  
  358. File: bison.info,  Node: Pure Calling,  Prev: Token Positions,  Up: Lexical
  359.  
  360. Calling for Pure Parsers
  361. ------------------------
  362.  
  363.    When you use the Bison declaration `%pure_parser' to request a pure,
  364. reentrant parser, the global communication variables `yylval' and
  365. `yylloc' cannot be used.  (*Note Pure Decl::.)  In such parsers the two
  366. global variables are replaced by pointers passed as arguments to
  367. `yylex'.  You must declare them as shown here, and pass the information
  368. back by storing it through those pointers.
  369.  
  370.      yylex (lvalp, llocp)
  371.           YYSTYPE *lvalp;
  372.           YYLTYPE *llocp;
  373.      {
  374.        ...
  375.        *lvalp = value;  /* Put value onto Bison stack.  */
  376.        return INT;      /* Return the type of the token.  */
  377.        ...
  378.      }
  379.  
  380.    If the grammar file does not use the `@' constructs to refer to
  381. textual positions, then the type `YYLTYPE' will not be defined.  In
  382. this case, omit the second argument; `yylex' will be called with only
  383. one argument.
  384.  
  385. File: bison.info,  Node: Error Reporting,  Next: Action Features,  Prev: Lexical,  Up: Interface
  386.  
  387. The Error Reporting Function `yyerror'
  388. ======================================
  389.  
  390.    The Bison parser detects a "parse error" or "syntax error" whenever
  391. it reads a token which cannot satisfy any syntax rule.  A action in the
  392. grammar can also explicitly proclaim an error, using the macro
  393. `YYERROR' (*note Action Features::.).
  394.  
  395.    The Bison parser expects to report the error by calling an error
  396. reporting function named `yyerror', which you must supply.  It is
  397. called by `yyparse' whenever a syntax error is found, and it receives
  398. one argument.  For a parse error, the string is always `"parse error"'.
  399.  
  400.    The parser can detect one other kind of error: stack overflow.  This
  401. happens when the input contains constructions that are very deeply
  402. nested.  It isn't likely you will encounter this, since the Bison
  403. parser extends its stack automatically up to a very large limit.  But
  404. if overflow happens, `yyparse' calls `yyerror' in the usual fashion,
  405. except that the argument string is `"parser stack overflow"'.
  406.  
  407.    The following definition suffices in simple programs:
  408.  
  409.      yyerror (s)
  410.           char *s;
  411.      {
  412.        fprintf (stderr, "%s\n", s);
  413.      }
  414.  
  415.    After `yyerror' returns to `yyparse', the latter will attempt error
  416. recovery if you have written suitable error recovery grammar rules
  417. (*note Error Recovery::.).  If recovery is impossible, `yyparse' will
  418. immediately return 1.
  419.  
  420.    The variable `yynerrs' contains the number of syntax errors
  421. encountered so far.  Normally this variable is global; but if you
  422. request a pure parser (*note Pure Decl::.) then it is a local variable
  423. which only the actions can access.
  424.  
  425. File: bison.info,  Node: Action Features,  Prev: Error Reporting,  Up: Interface
  426.  
  427. Special Features for Use in Actions
  428. ===================================
  429.  
  430.    Here is a table of Bison constructs, variables and macros that are
  431. useful in actions.
  432.  
  433. `$$'
  434.      Acts like a variable that contains the semantic value for the
  435.      grouping made by the current rule.  *Note Actions::.
  436.  
  437. `$N'
  438.      Acts like a variable that contains the semantic value for the Nth
  439.      component of the current rule.  *Note Actions::.
  440.  
  441. `$<TYPEALT>$'
  442.      Like `$$' but specifies alternative TYPEALT in the union specified
  443.      by the `%union' declaration.  *Note Action Types::.
  444.  
  445. `$<TYPEALT>N'
  446.      Like `$N' but specifies alternative TYPEALT in the union specified
  447.      by the `%union' declaration.  *Note Action Types::.
  448.  
  449. `YYABORT;'
  450.      Return immediately from `yyparse', indicating failure. *Note
  451.      Parser Function::.
  452.  
  453. `YYACCEPT;'
  454.      Return immediately from `yyparse', indicating success. *Note
  455.      Parser Function::.
  456.  
  457. `YYBACKUP (TOKEN, VALUE);'
  458.      Unshift a token.  This macro is allowed only for rules that reduce
  459.      a single value, and only when there is no look-ahead token. It
  460.      installs a look-ahead token with token type TOKEN and semantic
  461.      value VALUE; then it discards the value that was going to be
  462.      reduced by this rule.
  463.  
  464.      If the macro is used when it is not valid, such as when there is a
  465.      look-ahead token already, then it reports a syntax error with a
  466.      message `cannot back up' and performs ordinary error recovery.
  467.  
  468.      In either case, the rest of the action is not executed.
  469.  
  470. `YYEMPTY'
  471.      Value stored in `yychar' when there is no look-ahead token.
  472.  
  473. `YYERROR;'
  474.      Cause an immediate syntax error.  This statement initiates error
  475.      recovery just as if the parser itself had detected an error;
  476.      however, it does not call `yyerror', and does not print any
  477.      message.  If you want to print an error message, call `yyerror'
  478.      explicitly before the `YYERROR;' statement.  *Note Error
  479.      Recovery::.
  480.  
  481. `YYRECOVERING'
  482.      This macro stands for an expression that has the value 1 when the
  483.      parser is recovering from a syntax error, and 0 the rest of the
  484.      time. *Note Error Recovery::.
  485.  
  486. `yychar'
  487.      Variable containing the current look-ahead token.  (In a pure
  488.      parser, this is actually a local variable within `yyparse'.)  When
  489.      there is no look-ahead token, the value `YYEMPTY' is stored in the
  490.      variable. *Note Look-Ahead::.
  491.  
  492. `yyclearin;'
  493.      Discard the current look-ahead token.  This is useful primarily in
  494.      error rules.  *Note Error Recovery::.
  495.  
  496. `yyerrok;'
  497.      Resume generating error messages immediately for subsequent syntax
  498.      errors.  This is useful primarily in error rules.  *Note Error
  499.      Recovery::.
  500.  
  501. `@N'
  502.      Acts like a structure variable containing information on the line
  503.      numbers and column numbers of the Nth component of the current
  504.      rule.  The structure has four members, like this:
  505.  
  506.           struct {
  507.             int first_line, last_line;
  508.             int first_column, last_column;
  509.           };
  510.  
  511.      Thus, to get the starting line number of the third component, use
  512.      `@3.first_line'.
  513.  
  514.      In order for the members of this structure to contain valid
  515.      information, you must make `yylex' supply this information about
  516.      each token. If you need only certain members, then `yylex' need
  517.      only fill in those members.
  518.  
  519.      The use of this feature makes the parser noticeably slower.
  520.  
  521. File: bison.info,  Node: Algorithm,  Next: Error Recovery,  Prev: Interface,  Up: Top
  522.  
  523. The Bison Parser Algorithm
  524. **************************
  525.  
  526.    As Bison reads tokens, it pushes them onto a stack along with their
  527. semantic values.  The stack is called the "parser stack".  Pushing a
  528. token is traditionally called "shifting".
  529.  
  530.    For example, suppose the infix calculator has read `1 + 5 *', with a
  531. `3' to come.  The stack will have four elements, one for each token
  532. that was shifted.
  533.  
  534.    But the stack does not always have an element for each token read. 
  535. When the last N tokens and groupings shifted match the components of a
  536. grammar rule, they can be combined according to that rule.  This is
  537. called "reduction".  Those tokens and groupings are replaced on the
  538. stack by a single grouping whose symbol is the result (left hand side)
  539. of that rule. Running the rule's action is part of the process of
  540. reduction, because this is what computes the semantic value of the
  541. resulting grouping.
  542.  
  543.    For example, if the infix calculator's parser stack contains this:
  544.  
  545.      1 + 5 * 3
  546.  
  547. and the next input token is a newline character, then the last three
  548. elements can be reduced to 15 via the rule:
  549.  
  550.      expr: expr '*' expr;
  551.  
  552. Then the stack contains just these three elements:
  553.  
  554.      1 + 15
  555.  
  556. At this point, another reduction can be made, resulting in the single
  557. value 16.  Then the newline token can be shifted.
  558.  
  559.    The parser tries, by shifts and reductions, to reduce the entire
  560. input down to a single grouping whose symbol is the grammar's
  561. start-symbol (*note Language and Grammar::.).
  562.  
  563.    This kind of parser is known in the literature as a bottom-up parser.
  564.  
  565. * Menu:
  566.  
  567. * Look-Ahead::          Parser looks one token ahead when deciding what to do.
  568. * Shift/Reduce::        Conflicts: when either shifting or reduction is valid.
  569. * Precedence::          Operator precedence works by resolving conflicts.
  570. * Contextual Precedence:: When an operator's precedence depends on context.
  571. * Parser States::       The parser is a finite-state-machine with stack.
  572. * Reduce/Reduce::       When two rules are applicable in the same situation.
  573. * Mystery Conflicts::   Reduce/reduce conflicts that look unjustified.
  574. * Stack Overflow::      What happens when stack gets full.  How to avoid it.
  575.  
  576. File: bison.info,  Node: Look-Ahead,  Next: Shift/Reduce,  Prev: Algorithm,  Up: Algorithm
  577.  
  578. Look-Ahead Tokens
  579. =================
  580.  
  581.    The Bison parser does *not* always reduce immediately as soon as the
  582. last N tokens and groupings match a rule.  This is because such a
  583. simple strategy is inadequate to handle most languages.  Instead, when a
  584. reduction is possible, the parser sometimes "looks ahead" at the next
  585. token in order to decide what to do.
  586.  
  587.    When a token is read, it is not immediately shifted; first it
  588. becomes the "look-ahead token", which is not on the stack.  Now the
  589. parser can perform one or more reductions of tokens and groupings on
  590. the stack, while the look-ahead token remains off to the side.  When no
  591. more reductions should take place, the look-ahead token is shifted onto
  592. the stack.  This does not mean that all possible reductions have been
  593. done; depending on the token type of the look-ahead token, some rules
  594. may choose to delay their application.
  595.  
  596.    Here is a simple case where look-ahead is needed.  These three rules
  597. define expressions which contain binary addition operators and postfix
  598. unary factorial operators (`!'), and allow parentheses for grouping.
  599.  
  600.      expr:     term '+' expr
  601.              | term
  602.              ;
  603.      
  604.      term:     '(' expr ')'
  605.              | term '!'
  606.              | NUMBER
  607.              ;
  608.  
  609.    Suppose that the tokens `1 + 2' have been read and shifted; what
  610. should be done?  If the following token is `)', then the first three
  611. tokens must be reduced to form an `expr'.  This is the only valid
  612. course, because shifting the `)' would produce a sequence of symbols
  613. `term ')'', and no rule allows this.
  614.  
  615.    If the following token is `!', then it must be shifted immediately so
  616. that `2 !' can be reduced to make a `term'.  If instead the parser were
  617. to reduce before shifting, `1 + 2' would become an `expr'.  It would
  618. then be impossible to shift the `!' because doing so would produce on
  619. the stack the sequence of symbols `expr '!''.  No rule allows that
  620. sequence.
  621.  
  622.    The current look-ahead token is stored in the variable `yychar'.
  623. *Note Action Features::.
  624.  
  625. File: bison.info,  Node: Shift/Reduce,  Next: Precedence,  Prev: Look-Ahead,  Up: Algorithm
  626.  
  627. Shift/Reduce Conflicts
  628. ======================
  629.  
  630.    Suppose we are parsing a language which has if-then and if-then-else
  631. statements, with a pair of rules like this:
  632.  
  633.      if_stmt:
  634.                IF expr THEN stmt
  635.              | IF expr THEN stmt ELSE stmt
  636.              ;
  637.  
  638. (Here we assume that `IF', `THEN' and `ELSE' are terminal symbols for
  639. specific keyword tokens.)
  640.  
  641.    When the `ELSE' token is read and becomes the look-ahead token, the
  642. contents of the stack (assuming the input is valid) are just right for
  643. reduction by the first rule.  But it is also legitimate to shift the
  644. `ELSE', because that would lead to eventual reduction by the second
  645. rule.
  646.  
  647.    This situation, where either a shift or a reduction would be valid,
  648. is called a "shift/reduce conflict".  Bison is designed to resolve these
  649. conflicts by choosing to shift, unless otherwise directed by operator
  650. precedence declarations.  To see the reason for this, let's contrast it
  651. with the other alternative.
  652.  
  653.    Since the parser prefers to shift the `ELSE', the result is to attach
  654. the else-clause to the innermost if-statement, making these two inputs
  655. equivalent:
  656.  
  657.      if x then if y then win (); else lose;
  658.      
  659.      if x then do; if y then win (); else lose; end;
  660.  
  661.    But if the parser chose to reduce when possible rather than shift,
  662. the result would be to attach the else-clause to the outermost
  663. if-statement, making these two inputs equivalent:
  664.  
  665.      if x then if y then win (); else lose;
  666.      
  667.      if x then do; if y then win (); end; else lose;
  668.  
  669.    The conflict exists because the grammar as written is ambiguous:
  670. either parsing of the simple nested if-statement is legitimate.  The
  671. established convention is that these ambiguities are resolved by
  672. attaching the else-clause to the innermost if-statement; this is what
  673. Bison accomplishes by choosing to shift rather than reduce.  (It would
  674. ideally be cleaner to write an unambiguous grammar, but that is very
  675. hard to do in this case.) This particular ambiguity was first
  676. encountered in the specifications of Algol 60 and is called the
  677. "dangling `else'" ambiguity.
  678.  
  679.    To avoid warnings from Bison about predictable, legitimate
  680. shift/reduce conflicts, use the `%expect N' declaration.  There will be
  681. no warning as long as the number of shift/reduce conflicts is exactly N.
  682. *Note Expect Decl::.
  683.  
  684. File: bison.info,  Node: Precedence,  Next: Contextual Precedence,  Prev: Shift/Reduce,  Up: Algorithm
  685.  
  686. Operator Precedence
  687. ===================
  688.  
  689.    Another situation where shift/reduce conflicts appear is in
  690. arithmetic expressions.  Here shifting is not always the preferred
  691. resolution; the Bison declarations for operator precedence allow you to
  692. specify when to shift and when to reduce.
  693.  
  694. * Menu:
  695.  
  696. * Why Precedence::      An example showing why precedence is needed.
  697. * Using Precedence::    How to specify precedence in Bison grammars.
  698. * Precedence Examples:: How these features are used in the previous example.
  699. * How Precedence::      How they work.
  700.  
  701. File: bison.info,  Node: Why Precedence,  Next: Using Precedence,  Prev: Precedence,  Up: Precedence
  702.  
  703. When Precedence is Needed
  704. -------------------------
  705.  
  706.    Consider the following ambiguous grammar fragment (ambiguous because
  707. the input `1 - 2 * 3' can be parsed in two different ways):
  708.  
  709.      expr:     expr '-' expr
  710.              | expr '*' expr
  711.              | expr '<' expr
  712.              | '(' expr ')'
  713.              ...
  714.              ;
  715.  
  716. Suppose the parser has seen the tokens `1', `-' and `2'; should it
  717. reduce them via the rule for the addition operator?  It depends on the
  718. next token.  Of course, if the next token is `)', we must reduce;
  719. shifting is invalid because no single rule can reduce the token
  720. sequence `- 2 )' or anything starting with that.  But if the next token
  721. is `*' or `<', we have a choice: either shifting or reduction would
  722. allow the parse to complete, but with different results.
  723.  
  724.    To decide which one Bison should do, we must consider the results. 
  725. If the next operator token OP is shifted, then it must be reduced first
  726. in order to permit another opportunity to reduce the sum.  The result
  727. is (in effect) `1 - (2 OP 3)'.  On the other hand, if the subtraction
  728. is reduced before shifting OP, the result is `(1 - 2) OP 3'.  Clearly,
  729. then, the choice of shift or reduce should depend on the relative
  730. precedence of the operators `-' and OP: `*' should be shifted first,
  731. but not `<'.
  732.  
  733.    What about input such as `1 - 2 - 5'; should this be `(1 - 2) - 5'
  734. or should it be `1 - (2 - 5)'?  For most operators we prefer the
  735. former, which is called "left association".  The latter alternative,
  736. "right association", is desirable for assignment operators.  The choice
  737. of left or right association is a matter of whether the parser chooses
  738. to shift or reduce when the stack contains `1 - 2' and the look-ahead
  739. token is `-': shifting makes right-associativity.
  740.  
  741. File: bison.info,  Node: Using Precedence,  Next: Precedence Examples,  Prev: Why Precedence,  Up: Precedence
  742.  
  743. Specifying Operator Precedence
  744. ------------------------------
  745.  
  746.    Bison allows you to specify these choices with the operator
  747. precedence declarations `%left' and `%right'.  Each such declaration
  748. contains a list of tokens, which are operators whose precedence and
  749. associativity is being declared.  The `%left' declaration makes all
  750. those operators left-associative and the `%right' declaration makes
  751. them right-associative.  A third alternative is `%nonassoc', which
  752. declares that it is a syntax error to find the same operator twice "in a
  753. row".
  754.  
  755.    The relative precedence of different operators is controlled by the
  756. order in which they are declared.  The first `%left' or `%right'
  757. declaration in the file declares the operators whose precedence is
  758. lowest, the next such declaration declares the operators whose
  759. precedence is a little higher, and so on.
  760.  
  761. File: bison.info,  Node: Precedence Examples,  Next: How Precedence,  Prev: Using Precedence,  Up: Precedence
  762.  
  763. Precedence Examples
  764. -------------------
  765.  
  766.    In our example, we would want the following declarations:
  767.  
  768.      %left '<'
  769.      %left '-'
  770.      %left '*'
  771.  
  772.    In a more complete example, which supports other operators as well,
  773. we would declare them in groups of equal precedence.  For example,
  774. `'+'' is declared with `'-'':
  775.  
  776.      %left '<' '>' '=' NE LE GE
  777.      %left '+' '-'
  778.      %left '*' '/'
  779.  
  780. (Here `NE' and so on stand for the operators for "not equal" and so on.
  781.  We assume that these tokens are more than one character long and
  782. therefore are represented by names, not character literals.)
  783.  
  784. File: bison.info,  Node: How Precedence,  Prev: Precedence Examples,  Up: Precedence
  785.  
  786. How Precedence Works
  787. --------------------
  788.  
  789.    The first effect of the precedence declarations is to assign
  790. precedence levels to the terminal symbols declared.  The second effect
  791. is to assign precedence levels to certain rules: each rule gets its
  792. precedence from the last terminal symbol mentioned in the components. 
  793. (You can also specify explicitly the precedence of a rule.  *Note
  794. Contextual Precedence::.)
  795.  
  796.    Finally, the resolution of conflicts works by comparing the
  797. precedence of the rule being considered with that of the look-ahead
  798. token.  If the token's precedence is higher, the choice is to shift. 
  799. If the rule's precedence is higher, the choice is to reduce.  If they
  800. have equal precedence, the choice is made based on the associativity of
  801. that precedence level.  The verbose output file made by `-v' (*note
  802. Invocation::.) says how each conflict was resolved.
  803.  
  804.    Not all rules and not all tokens have precedence.  If either the
  805. rule or the look-ahead token has no precedence, then the default is to
  806. shift.
  807.  
  808. File: bison.info,  Node: Contextual Precedence,  Next: Parser States,  Prev: Precedence,  Up: Algorithm
  809.  
  810. Context-Dependent Precedence
  811. ============================
  812.  
  813.    Often the precedence of an operator depends on the context.  This
  814. sounds outlandish at first, but it is really very common.  For example,
  815. a minus sign typically has a very high precedence as a unary operator,
  816. and a somewhat lower precedence (lower than multiplication) as a binary
  817. operator.
  818.  
  819.    The Bison precedence declarations, `%left', `%right' and
  820. `%nonassoc', can only be used once for a given token; so a token has
  821. only one precedence declared in this way.  For context-dependent
  822. precedence, you need to use an additional mechanism: the `%prec'
  823. modifier for rules.
  824.  
  825.    The `%prec' modifier declares the precedence of a particular rule by
  826. specifying a terminal symbol whose precedence should be used for that
  827. rule. It's not necessary for that symbol to appear otherwise in the
  828. rule.  The modifier's syntax is:
  829.  
  830.      %prec TERMINAL-SYMBOL
  831.  
  832. and it is written after the components of the rule.  Its effect is to
  833. assign the rule the precedence of TERMINAL-SYMBOL, overriding the
  834. precedence that would be deduced for it in the ordinary way.  The
  835. altered rule precedence then affects how conflicts involving that rule
  836. are resolved (*note Precedence::.).
  837.  
  838.    Here is how `%prec' solves the problem of unary minus.  First,
  839. declare a precedence for a fictitious terminal symbol named `UMINUS'. 
  840. There are no tokens of this type, but the symbol serves to stand for its
  841. precedence:
  842.  
  843.      ...
  844.      %left '+' '-'
  845.      %left '*'
  846.      %left UMINUS
  847.  
  848.    Now the precedence of `UMINUS' can be used in specific rules:
  849.  
  850.      exp:    ...
  851.              | exp '-' exp
  852.              ...
  853.              | '-' exp %prec UMINUS
  854.  
  855. File: bison.info,  Node: Parser States,  Next: Reduce/Reduce,  Prev: Contextual Precedence,  Up: Algorithm
  856.  
  857. Parser States
  858. =============
  859.  
  860.    The function `yyparse' is implemented using a finite-state machine.
  861. The values pushed on the parser stack are not simply token type codes;
  862. they represent the entire sequence of terminal and nonterminal symbols
  863. at or near the top of the stack.  The current state collects all the
  864. information about previous input which is relevant to deciding what to
  865. do next.
  866.  
  867.    Each time a look-ahead token is read, the current parser state
  868. together with the type of look-ahead token are looked up in a table. 
  869. This table entry can say, "Shift the look-ahead token."  In this case,
  870. it also specifies the new parser state, which is pushed onto the top of
  871. the parser stack.  Or it can say, "Reduce using rule number N." This
  872. means that a certain of tokens or groupings are taken off the top of
  873. the stack, and replaced by one grouping.  In other words, that number
  874. of states are popped from the stack, and one new state is pushed.
  875.  
  876.    There is one other alternative: the table can say that the
  877. look-ahead token is erroneous in the current state.  This causes error
  878. processing to begin (*note Error Recovery::.).
  879.  
  880. File: bison.info,  Node: Reduce/Reduce,  Next: Mystery Conflicts,  Prev: Parser States,  Up: Algorithm
  881.  
  882. Reduce/Reduce Conflicts
  883. =======================
  884.  
  885.    A reduce/reduce conflict occurs if there are two or more rules that
  886. apply to the same sequence of input.  This usually indicates a serious
  887. error in the grammar.
  888.  
  889.    For example, here is an erroneous attempt to define a sequence of
  890. zero or more `word' groupings.
  891.  
  892.      sequence: /* empty */
  893.                      { printf ("empty sequence\n"); }
  894.              | word
  895.                      { printf ("single word %s\n", $1); }
  896.              | sequence word
  897.                      { printf ("added word %s\n", $2); }
  898.              ;
  899.  
  900. The error is an ambiguity: there is more than one way to parse a single
  901. `word' into a `sequence'.  It could be reduced directly via the second
  902. rule.  Alternatively, nothing-at-all could be reduced into a `sequence'
  903. via the first rule, and this could be combined with the `word' using
  904. the third rule.
  905.  
  906.    You might think that this is a distinction without a difference,
  907. because it does not change whether any particular input is valid or
  908. not.  But it does affect which actions are run.  One parsing order runs
  909. the second rule's action; the other runs the first rule's action and
  910. the third rule's action. In this example, the output of the program
  911. changes.
  912.  
  913.    Bison resolves a reduce/reduce conflict by choosing to use the rule
  914. that appears first in the grammar, but it is very risky to rely on
  915. this.  Every reduce/reduce conflict must be studied and usually
  916. eliminated.  Here is the proper way to define `sequence':
  917.  
  918.      sequence: /* empty */
  919.                      { printf ("empty sequence\n"); }
  920.              | sequence word
  921.                      { printf ("added word %s\n", $2); }
  922.              ;
  923.  
  924.    Here is another common error that yields a reduce/reduce conflict:
  925.  
  926.      sequence: /* empty */
  927.              | sequence words
  928.              | sequence redirects
  929.              ;
  930.      
  931.      words:    /* empty */
  932.              | words word
  933.              ;
  934.      
  935.      redirects:/* empty */
  936.              | redirects redirect
  937.              ;
  938.  
  939. The intention here is to define a sequence which can contain either
  940. `word' or `redirect' groupings.  The individual definitions of
  941. `sequence', `words' and `redirects' are error-free, but the three
  942. together make a subtle ambiguity: even an empty input can be parsed in
  943. infinitely many ways!
  944.  
  945.    Consider: nothing-at-all could be a `words'.  Or it could be two
  946. `words' in a row, or three, or any number.  It could equally well be a
  947. `redirects', or two, or any number.  Or it could be a `words' followed
  948. by three `redirects' and another `words'.  And so on.
  949.  
  950.    Here are two ways to correct these rules.  First, to make it a
  951. single level of sequence:
  952.  
  953.      sequence: /* empty */
  954.              | sequence word
  955.              | sequence redirect
  956.              ;
  957.  
  958.    Second, to prevent either a `words' or a `redirects' from being
  959. empty:
  960.  
  961.      sequence: /* empty */
  962.              | sequence words
  963.              | sequence redirects
  964.              ;
  965.      
  966.      words:    word
  967.              | words word
  968.              ;
  969.      
  970.      redirects:redirect
  971.              | redirects redirect
  972.              ;
  973.  
  974. File: bison.info,  Node: Mystery Conflicts,  Next: Stack Overflow,  Prev: Reduce/Reduce,  Up: Algorithm
  975.  
  976. Mysterious Reduce/Reduce Conflicts
  977. ==================================
  978.  
  979.    Sometimes reduce/reduce conflicts can occur that don't look
  980. warranted. Here is an example:
  981.  
  982.      %token ID
  983.      
  984.      %%
  985.      def:    param_spec return_spec ','
  986.              ;
  987.      param_spec:
  988.                   type
  989.              |    name_list ':' type
  990.              ;
  991.      return_spec:
  992.                   type
  993.              |    name ':' type
  994.              ;
  995.      type:        ID
  996.              ;
  997.      name:        ID
  998.              ;
  999.      name_list:
  1000.                   name
  1001.              |    name ',' name_list
  1002.              ;
  1003.  
  1004.    It would seem that this grammar can be parsed with only a single
  1005. token of look-ahead: when a `param_spec' is being read, an `ID' is a
  1006. `name' if a comma or colon follows, or a `type' if another `ID'
  1007. follows.  In other words, this grammar is LR(1).
  1008.  
  1009.    However, Bison, like most parser generators, cannot actually handle
  1010. all LR(1) grammars.  In this grammar, two contexts, that after an `ID'
  1011. at the beginning of a `param_spec' and likewise at the beginning of a
  1012. `return_spec', are similar enough that Bison assumes they are the same.
  1013.  They appear similar because the same set of rules would be active--the
  1014. rule for reducing to a `name' and that for reducing to a `type'.  Bison
  1015. is unable to determine at that stage of processing that the rules would
  1016. require different look-ahead tokens in the two contexts, so it makes a
  1017. single parser state for them both.  Combining the two contexts causes a
  1018. conflict later.  In parser terminology, this occurrence means that the
  1019. grammar is not LALR(1).
  1020.  
  1021.    In general, it is better to fix deficiencies than to document them. 
  1022. But this particular deficiency is intrinsically hard to fix; parser
  1023. generators that can handle LR(1) grammars are hard to write and tend to
  1024. produce parsers that are very large.  In practice, Bison is more useful
  1025. as it is now.
  1026.  
  1027.    When the problem arises, you can often fix it by identifying the two
  1028. parser states that are being confused, and adding something to make them
  1029. look distinct.  In the above example, adding one rule to `return_spec'
  1030. as follows makes the problem go away:
  1031.  
  1032.      %token BOGUS
  1033.      ...
  1034.      %%
  1035.      ...
  1036.      return_spec:
  1037.                   type
  1038.              |    name ':' type
  1039.              /* This rule is never used.  */
  1040.              |    ID BOGUS
  1041.              ;
  1042.  
  1043.    This corrects the problem because it introduces the possibility of an
  1044. additional active rule in the context after the `ID' at the beginning of
  1045. `return_spec'.  This rule is not active in the corresponding context in
  1046. a `param_spec', so the two contexts receive distinct parser states. As
  1047. long as the token `BOGUS' is never generated by `yylex', the added rule
  1048. cannot alter the way actual input is parsed.
  1049.  
  1050.    In this particular example, there is another way to solve the
  1051. problem: rewrite the rule for `return_spec' to use `ID' directly
  1052. instead of via `name'.  This also causes the two confusing contexts to
  1053. have different sets of active rules, because the one for `return_spec'
  1054. activates the altered rule for `return_spec' rather than the one for
  1055. `name'.
  1056.  
  1057.      param_spec:
  1058.                   type
  1059.              |    name_list ':' type
  1060.              ;
  1061.      return_spec:
  1062.                   type
  1063.              |    ID ':' type
  1064.              ;
  1065.  
  1066. File: bison.info,  Node: Stack Overflow,  Prev: Mystery Conflicts,  Up: Algorithm
  1067.  
  1068. Stack Overflow, and How to Avoid It
  1069. ===================================
  1070.  
  1071.    The Bison parser stack can overflow if too many tokens are shifted
  1072. and not reduced.  When this happens, the parser function `yyparse'
  1073. returns a nonzero value, pausing only to call `yyerror' to report the
  1074. overflow.
  1075.  
  1076.    By defining the macro `YYMAXDEPTH', you can control how deep the
  1077. parser stack can become before a stack overflow occurs.  Define the
  1078. macro with a value that is an integer.  This value is the maximum number
  1079. of tokens that can be shifted (and not reduced) before overflow. It
  1080. must be a constant expression whose value is known at compile time.
  1081.  
  1082.    The stack space allowed is not necessarily allocated.  If you
  1083. specify a large value for `YYMAXDEPTH', the parser actually allocates a
  1084. small stack at first, and then makes it bigger by stages as needed. 
  1085. This increasing allocation happens automatically and silently. 
  1086. Therefore, you do not need to make `YYMAXDEPTH' painfully small merely
  1087. to save space for ordinary inputs that do not need much stack.
  1088.  
  1089.    The default value of `YYMAXDEPTH', if you do not define it, is 10000.
  1090.  
  1091.    You can control how much stack is allocated initially by defining the
  1092. macro `YYINITDEPTH'.  This value too must be a compile-time constant
  1093. integer.  The default is 200.
  1094.  
  1095. File: bison.info,  Node: Error Recovery,  Next: Context Dependency,  Prev: Algorithm,  Up: Top
  1096.  
  1097. Error Recovery
  1098. **************
  1099.  
  1100.    It is not usually acceptable to have a program terminate on a parse
  1101. error.  For example, a compiler should recover sufficiently to parse the
  1102. rest of the input file and check it for errors; a calculator should
  1103. accept another expression.
  1104.  
  1105.    In a simple interactive command parser where each input is one line,
  1106. it may be sufficient to allow `yyparse' to return 1 on error and have
  1107. the caller ignore the rest of the input line when that happens (and
  1108. then call `yyparse' again).  But this is inadequate for a compiler,
  1109. because it forgets all the syntactic context leading up to the error. 
  1110. A syntax error deep within a function in the compiler input should not
  1111. cause the compiler to treat the following line like the beginning of a
  1112. source file.
  1113.  
  1114.    You can define how to recover from a syntax error by writing rules to
  1115. recognize the special token `error'.  This is a terminal symbol that is
  1116. always defined (you need not declare it) and reserved for error
  1117. handling.  The Bison parser generates an `error' token whenever a
  1118. syntax error happens; if you have provided a rule to recognize this
  1119. token in the current context, the parse can continue.
  1120.  
  1121.    For example:
  1122.  
  1123.      stmnts:  /* empty string */
  1124.              | stmnts '\n'
  1125.              | stmnts exp '\n'
  1126.              | stmnts error '\n'
  1127.  
  1128.    The fourth rule in this example says that an error followed by a
  1129. newline makes a valid addition to any `stmnts'.
  1130.  
  1131.    What happens if a syntax error occurs in the middle of an `exp'?  The
  1132. error recovery rule, interpreted strictly, applies to the precise
  1133. sequence of a `stmnts', an `error' and a newline.  If an error occurs in
  1134. the middle of an `exp', there will probably be some additional tokens
  1135. and subexpressions on the stack after the last `stmnts', and there will
  1136. be tokens to read before the next newline.  So the rule is not
  1137. applicable in the ordinary way.
  1138.  
  1139.    But Bison can force the situation to fit the rule, by discarding
  1140. part of the semantic context and part of the input.  First it discards
  1141. states and objects from the stack until it gets back to a state in
  1142. which the `error' token is acceptable.  (This means that the
  1143. subexpressions already parsed are discarded, back to the last complete
  1144. `stmnts'.)  At this point the `error' token can be shifted.  Then, if
  1145. the old look-ahead token is not acceptable to be shifted next, the
  1146. parser reads tokens and discards them until it finds a token which is
  1147. acceptable.  In this example, Bison reads and discards input until the
  1148. next newline so that the fourth rule can apply.
  1149.  
  1150.    The choice of error rules in the grammar is a choice of strategies
  1151. for error recovery.  A simple and useful strategy is simply to skip the
  1152. rest of the current input line or current statement if an error is
  1153. detected:
  1154.  
  1155.      stmnt: error ';'  /* on error, skip until ';' is read */
  1156.  
  1157.    It is also useful to recover to the matching close-delimiter of an
  1158. opening-delimiter that has already been parsed.  Otherwise the
  1159. close-delimiter will probably appear to be unmatched, and generate
  1160. another, spurious error message:
  1161.  
  1162.      primary:  '(' expr ')'
  1163.              | '(' error ')'
  1164.              ...
  1165.              ;
  1166.  
  1167.    Error recovery strategies are necessarily guesses.  When they guess
  1168. wrong, one syntax error often leads to another.  In the above example,
  1169. the error recovery rule guesses that an error is due to bad input
  1170. within one `stmnt'.  Suppose that instead a spurious semicolon is
  1171. inserted in the middle of a valid `stmnt'.  After the error recovery
  1172. rule recovers from the first error, another syntax error will be found
  1173. straightaway, since the text following the spurious semicolon is also
  1174. an invalid `stmnt'.
  1175.  
  1176.    To prevent an outpouring of error messages, the parser will output
  1177. no error message for another syntax error that happens shortly after
  1178. the first; only after three consecutive input tokens have been
  1179. successfully shifted will error messages resume.
  1180.  
  1181.    Note that rules which accept the `error' token may have actions, just
  1182. as any other rules can.
  1183.  
  1184.    You can make error messages resume immediately by using the macro
  1185. `yyerrok' in an action.  If you do this in the error rule's action, no
  1186. error messages will be suppressed.  This macro requires no arguments;
  1187. `yyerrok;' is a valid C statement.
  1188.  
  1189.    The previous look-ahead token is reanalyzed immediately after an
  1190. error.  If this is unacceptable, then the macro `yyclearin' may be used
  1191. to clear this token.  Write the statement `yyclearin;' in the error
  1192. rule's action.
  1193.  
  1194.    For example, suppose that on a parse error, an error handling
  1195. routine is called that advances the input stream to some point where
  1196. parsing should once again commence.  The next symbol returned by the
  1197. lexical scanner is probably correct.  The previous look-ahead token
  1198. ought to be discarded with `yyclearin;'.
  1199.  
  1200.    The macro `YYRECOVERING' stands for an expression that has the value
  1201. 1 when the parser is recovering from a syntax error, and 0 the rest of
  1202. the time.  A value of 1 indicates that error messages are currently
  1203. suppressed for new syntax errors.
  1204.  
  1205. File: bison.info,  Node: Context Dependency,  Next: Debugging,  Prev: Error Recovery,  Up: Top
  1206.  
  1207. Handling Context Dependencies
  1208. *****************************
  1209.  
  1210.    The Bison paradigm is to parse tokens first, then group them into
  1211. larger syntactic units.  In many languages, the meaning of a token is
  1212. affected by its context.  Although this violates the Bison paradigm,
  1213. certain techniques (known as "kludges") may enable you to write Bison
  1214. parsers for such languages.
  1215.  
  1216. * Menu:
  1217.  
  1218. * Semantic Tokens::     Token parsing can depend on the semantic context.
  1219. * Lexical Tie-ins::     Token parsing can depend on the syntactic context.
  1220. * Tie-in Recovery::     Lexical tie-ins have implications for how
  1221.                           error recovery rules must be written.
  1222.  
  1223.    (Actually, "kludge" means any technique that gets its job done but is
  1224. neither clean nor robust.)
  1225.